/**
 * Created by wenguangjia on 2017/4/27.
 */
(function () {
    'use strict';

    angular
        .module('logcenterApp')
        .controller('commLogController', commLogController);
    commLogController.$inject = ['$scope', 'searchService','toaster', '$stateParams'];
    function commLogController($scope, searchService,toaster,$stateParams) {
        var notify = function (type, title, message) {
            toaster.pop(type, title, message);
        };
        var isLoadMore = true;
        var isFirstLoad = true;
        $scope.resp = [];
        $scope.param = {
            tc_no: null,
            src_sys: null,
            dst_sys: null,
            startTime: getToday00Clock(),
            endTime: getToday11Clock(),
            type: $stateParams.type,
            success: "all",
            uuid: $stateParams.uuid
        };
        $scope.isSuccess = "all";

        //generate elasticSearch query template
        function generate() {
            var data = {
                "query": {
                    "bool": {
                        "must": [
                            {"terms":{"progress_seq":[200,210]}}
                        ],
                        "must_not":[
                            {"terms":{"uuid":["<NULL-GUID>","                "]}}
                        ],
                        "filter": []
                    }
                },
                "size": 0,
                "aggs": {
                    "byUuid": {
                        "terms": {
                            "field": "uuid",
                            "order":{"_term":"asc"},
                            "size": 500
                        },
                        "aggs": {
                            "topHit": {
                                "top_hits": {
                                    "sort": [
                                        {
                                            "progress_seq": {
                                                "order": "asc"
                                            }
                                        },
                                        {
                                            "@timestamp": {
                                                "order": "asc"
                                            }
                                        }
                                    ],
                                    "size": 1
                                }
                            }
                        }
                    }
                }
            };
            var obj = data['query']['bool'];

            if($scope.param.type == 'Routing-sync'){
                obj.must[0].terms.progress_seq.length = 0;
                obj.must[0].terms.progress_seq.push(100);
            }
            if ($scope.param.uuid != undefined && $scope.param.uuid != null && $scope.param.uuid != "") {
                var arrayObj =  {"term":{"uuid": $scope.param.uuid}};
                obj.filter.push(arrayObj);
            }
            if ($scope.param.partition != undefined && $scope.param.partition != null && $scope.param.partition != "") {
                var arrayObj = {"term": {"partition": $scope.param.partition}};
                obj.filter.push(arrayObj);
            }
            if ($scope.param.tc_no != null && $scope.param.tc_no != "") {
                var arrayObj = {"wildcard": {"tc_no": $scope.param.tc_no}};
                obj.must.push(arrayObj);
            }

            if ($scope.param.src_sys != undefined && $scope.param.src_sys != null && $scope.param.src_sys != "") {
                var arrayObj = {"term": {"src_sys": $scope.param.src_sys}};
                obj.filter.push(arrayObj);
            }
            if ($scope.param.dst_sys != undefined && $scope.param.dst_sys != null && $scope.param.dst_sys != "") {
                var arrayObj = {"term": {"dst_sys": $scope.param.dst_sys}};
                obj.filter.push(arrayObj);
            }

            if ($scope.param.type != "") {
                var arrayObj = {"match_phrase": {"logmsg": $scope.param.type}};
                obj.must.push(arrayObj);
            }

            if ($scope.param.startTime != null && $scope.param.endTime == null) {
                var arrayObj = {"range": {"@timestamp": {"gte": $scope.param.startTime}}};
                obj.filter.push(arrayObj);
            } else if ($scope.param.startTime == null && $scope.param.endTime != null) {
                var arrayObj = {"range": {"@timestamp": {"lt": $scope.param.endTime}}};
                obj.filter.push(arrayObj);
            } else if ($scope.param.startTime != null && $scope.param.endTime != null) {
                var arrayObj = {
                    "range": {
                        "@timestamp": {
                            "gte": $scope.param.startTime,
                            "lt": $scope.param.endTime
                        }
                    }
                };
                obj.filter.push(arrayObj);
            }
            return data;
        }

        function generate2(){
            var data = {
                "query": {
                    "bool": {
                        "must": {"terms":{"uuid":[]}},
                        "filter": []
                    }
                },
                "size": 0,
                "aggs": {
                    "byUuid": {
                        "terms": {
                            "field": "uuid",
                            "order":{"_term":"asc"},
                            "size": 500
                        },
                        "aggs": {
                            "topHit": {
                                "top_hits": {
                                    "sort": [
                                        {
                                            "progress_seq": {
                                                "order": "desc"
                                            }
                                        },
                                        {
                                            "@timestamp": {
                                                "order": "desc"
                                            }
                                        }
                                    ],
                                    "size": 1
                                }
                            }
                        }
                    }
                }
            };
            return data;
        }

        var req = null;
        $scope.query = function () {
            req = generate();
            if($scope.param.type == 'Routing-sync'){
                $scope.deployGrid.hideColumn(5);
            }else{
                $scope.deployGrid.showColumn(5);
            }
            $scope.commLogGridOptions.dataSource.read();
        };


        /**
         * grid
         * @type {*[]}
         */
        var columns = [
            {field: "src_sys", title: "源分区", width: "90px"},
            {field: "dst_sys", title: "目标分区", width: "90px"},
            {field: "tc_no", title: "电文号", width: "80px"},
            {field: "time", title: "时间", width: "160px"},
            {
                field: "progress",
                title: "进度",
                width: "300px"
            },
            {
                field: "command", title: "操作", width: "120px",
                template: function (dataItem) {
                    var result = '<kendo-button class="k-primary" ng-click="click(dataItem)">电文拆分</kendo-button>';
                    return result;
                }
            },
        ];
        $scope.EiInfoWinOptions = {
            width:"60%",
            height:"60%",
            modal: true
        };
        $scope.EiInfoWin = {
            title: '电文拆分',
            modal: true,
            visible: false
        };

        $scope.fields=[];
        $scope.table = null;
        $scope.values = [];
        var EiInfo = null;
        $scope.selectTable=function(){
            console.log($scope.table);
            angular.forEach(EiInfo.Tables,function(item){
                if($scope.table == item.Name){
                    $scope.values.length=0;
                    $scope.fields.length = 0;

                    //获取列名
                    for(var i in item.Table[0]){
                        $scope.fields.push(i);
                    }
                    //获取这表的所有数据
                    angular.forEach(item.Table,function(k){
                        var array = [];
                        for(var i in k){
                            array.push({value:k[i]});
                        }
                        $scope.values.push(array);
                    });
                }
            })
        };
        $scope.click=function(dataItem){
            if(dataItem.progress.indexOf('DEST')!=-1){
                var data = {
                    "query": {
                        "bool": {
                            "must": [
                                {"term": {"uuid": dataItem.uuid}},
                                {"term": {"progress_seq": 502}}
                            ],
                            "filter": []
                        }
                    },
                    "size": 1,
                    "from": 0
                };

                searchService.query(data, null, "comm").then(
                    function(resp){
                        var EiInfoStr = {TcNo:resp.data.hits.hits[0]._source.tc_no,BaseString:resp.data.hits.hits[0]._source.logmsg};
                        searchService.getEiInfo(EiInfoStr).then(
                            function(resp){
                                console.log(resp);
                                EiInfo=resp;
                                $scope.values.length=0;
                                $scope.fields.length=0;
                                $scope.tables = [];
                                //获取所有表名
                                angular.forEach(resp.Tables,function(item){
                                    $scope.tables.push({name:item.Name});
                                });
                                //获取第一张表的列
                                for(var i in resp.Tables[0].Table[0]){
                                    $scope.fields.push(i);
                                }
                                //获取第一张表的所有数据
                                angular.forEach(resp.Tables[0].Table,function(k){
                                    var array = [];
                                    for(var i in k){
                                        array.push({value:k[i]});
                                    }
                                    $scope.values.push(array);
                                });
                                $scope.table=$scope.tables[0].name;
                                $scope.EiInfoWin.center();
                                $scope.EiInfoWin.open();
                            },function(err){
                                notify("warn",'警告',err.data);
                            }
                        )
                    },function(err){
                        console.log(err);
                    }
                );
            }else{
                notify("warn",'警告','无法解析电文，电文不存在');
            }
        };

        $scope.queryLog = function(dataItem){
            localStorage.setItem("commlogObj", JSON.stringify(dataItem));
            var a = document.createElement('a');
            a.href = '#/log/commlogConsole';
            a.target = '_blank';
            a.click();
        };

        $scope.commLogGridOptions = {
            selectable: "row",
            scrollable: true,
            sortable: true,
            resizable: true,
            columns: columns,
            columnMenu: true,
            pageable: {
                refresh: true,
                pageSizes: true,
                buttonCount: 5
            },
            detailExpand: function(e) {
                var rows = e.sender.tbody[0].rows;
                for(var i = 0; i<rows.length;i++){
                    if(e.masterRow[0].outerText!=rows[i].outerText){
                        $scope.deployGrid.collapseRow(rows[i]);
                    }
                }
                var uuid = e.sender.dataItem(e.masterRow).uuid;
                queryDetail(uuid);
            }
        };

        $scope.commLogGridOptions.dataSource = new kendo.data.DataSource({
            autoBind: true,
            transport: {
                read: function (e) {
                    req = generate();
                    searchService.query(req, null, "comm").then(
                        function (resp) {
                            var bucketsArr = resp.data.aggregations.byUuid.buckets;
                            var array = [];
                            var array2 = [];
                            var data = generate2();
                            angular.forEach(bucketsArr, function (item) {
                                var obj = item.topHit.hits.hits[0]._source;
                                obj.time = obj['@timestamp'];
                                obj.time = getDate(obj.time);
                                array.push(obj);
                                data.query.bool.must.terms['uuid'].push(obj.uuid);
                            });
                            searchService.query(data, null, "comm").then(
                                function (resp2) {
                                    var count = 0;
                                    var bucketsArr2 = resp2.data.aggregations.byUuid.buckets;
                                    angular.forEach(bucketsArr2, function (item) {
                                        var obj = item.topHit.hits.hits[0]._source;
                                        array[count].progress = obj.progress;

                                        if ($scope.param.success == 'all') {
                                            array2.push(array[count]);
                                        } else if ($scope.param.success == 'true') {
                                            if($scope.param.type == 'Routing-async' && obj.progress.indexOf("FINISH") != -1){
                                                array2.push(array[count]);
                                            }else if($scope.param.type == 'Routing-sync' && obj.progress.indexOf("SUCCESS") != -1){
                                                array2.push(array[count]);
                                            }

                                        } else if ($scope.param.success == 'false') {
                                            if($scope.param.type == 'Routing-async' && obj.progress.indexOf("FINISH") == -1){
                                                array2.push(array[count]);
                                            }else if($scope.param.type == 'Routing-sync' && obj.progress.indexOf("SUCCESS") == -1){
                                                array2.push(array[count]);
                                            }
                                        }
                                        count++;
                                    });
                                    e.success(array2);
                                }, function (error) {
                                    e.error(error);
                                }
                            )
                        }, function (error) {
                            e.error(error);
                        }
                    )

                },
                parameterMap: function (options, operation) {
                    if (operation !== "read" && options.models) {
                        return {models: kendo.stringify(options.models)};
                    }
                }
            },
            requestStart: function (e) {
                if (isFirstLoad && $stateParams.uuid == null) {
                    e.preventDefault();
                    isFirstLoad = false;
                }
            },
            // schema: {
            //     model: $scope.deployModel
            // },
            batch: true,
            pageSize: 20
        });

        $scope.detailArr = [];
        var queryDetail = function(uuid){
            $scope.detailArr.length = 0;
            var data = {
                "query": {
                    "bool": {
                        "must": [
                            {"term": {"uuid": uuid}}
                        ],
                        "filter": []
                    }
                },
                "sort": [
                    {"progress_seq":{"order":"asc"}},{"@timestamp": {"order": "asc"}}
                ],
                "size": 500,
                "from": 0
            };

            searchService.query(data, null, "comm").then(
                function(resp){
                    $scope.detailArr = resp.data.hits.hits;
                    angular.forEach($scope.detailArr,function(item){
                        if(item._source.logtime.indexOf("-")!=-1){
                            var time = item._source.logtime;
                            var times = time.split("-");
                            item._source.logtime = "";
                            for(var i=0;i<times.length;i++){
                                item._source.logtime += times[i];
                            }

                        }
                    })
                },function(err){
                    console.log(err);
                }
            );
        };

    }


})();
